package com.yuer.rpc.chat;

import com.yuer.rpc.netty_base.NettyClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

public class NettyChatClient {
    private String iphost;
    private int port;

    public NettyChatClient(String iphost, int port) {
        this.iphost = iphost;
        this.port = port;
    }



    public void  run(){

        EventLoopGroup nioEventLoopGroup = null;
        try {
            nioEventLoopGroup = new NioEventLoopGroup();

            Bootstrap bootstrap = new Bootstrap();

            bootstrap.group(nioEventLoopGroup);
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    socketChannel.pipeline().addLast(new StringDecoder());
                    socketChannel.pipeline().addLast(new StringEncoder());

                    // 初始化之后，向 pipeline添加自定义处理的handher
                    socketChannel.pipeline().addLast(new NettyChatClientHandler());
                }
            });

            ChannelFuture connect = bootstrap.connect(getIphost(), getPort()).sync();
            Channel channel = connect.channel();
            System.out.println("----------"+"客户端启动就行，地址为："+channel.localAddress().toString().substring(1)+"----------");
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()){
                String s = scanner.nextLine();
                channel.writeAndFlush(s);
            }
            connect.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            nioEventLoopGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        NettyChatClient nettyChatClient = new NettyChatClient("127.0.0.1",9999);
        nettyChatClient.run();
    }

    public String getIphost() {
        return iphost;
    }

    public int getPort() {
        return port;
    }

}
